package com.dm.library.http;

import android.content.Context;
import android.text.TextUtils;

import com.dm.library.http.base.HttpBase;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.DMLog;
import com.dm.library.utils.StringUtils;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.GetBuilder;
import com.zhy.http.okhttp.builder.OtherRequestBuilder;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.builder.PostStringBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * 版 权: 深圳市迪蒙网络科技有限公司
 * 描 述:
 * 修 改 人: sushuo
 * 修改时间: 2016-12-20
 */
public class DMOKHttpUtils extends HttpBase {

    private static DMOKHttpUtils mInstance;
    private Gson mGson;

    private DMOKHttpUtils() {
        mGson = new Gson();
    }

    public static DMOKHttpUtils getInstance() {
        if (mInstance == null) {
            synchronized (DMOKHttpUtils.class) {
                if (mInstance == null) {
                    mInstance = new DMOKHttpUtils();
                }
            }
        }
        return mInstance;
    }

    @Override
    protected <T> void getData(final Context context, String url, HttpParams params, final RequestCallBack<T> callback) {
        GetBuilder getBuilder = OkHttpUtils.get().url(url);
        if (!TextUtils.isEmpty(TokenManager.getInstance().getToken(context))) {
            getBuilder.addHeader("Authorization", TokenManager.getInstance().getToken(context));
        }
        if (params != null) {
            getBuilder.params(params.toMapParams());
        }
        getBuilder.build().execute(new StringCallback() {
            @Override
            public void onBefore(Request request, int id) {
                if (callback != null) {
                    callback.onStart();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                DMOKHttpUtils.this.onJsonResponse(context, response, callback);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                if (callback != null) {
                    callback.onFailure(getFailedString(e));
                }
            }
        });

    }

    @Override
    protected <T> void postData(final Context context, String url, HttpParams params, final RequestCallBack<T> callback) {
        DMLog.i(TAG, "url：" + url);
        PostStringBuilder postStringBuilder = OkHttpUtils.postString().url(url).mediaType(MediaType.parse("application/json; charset=utf-8"));
        String token = TokenManager.getInstance().getToken(context);
        if (!TextUtils.isEmpty(token)) {
            postStringBuilder.addHeader("Authorization", token);
        } else {
            postStringBuilder.addHeader("Authorization", "token");
        }
        if (params != null) {
            params.put("opSource", "3"); //3:安卓 4:苹果
            postStringBuilder.content(params.toString());
        }
        postStringBuilder.build().execute(new StringCallback() {
            @Override
            public void onBefore(Request request, int id) {
                if (callback != null) {
                    callback.onStart();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                DMOKHttpUtils.this.onJsonResponse(context, response, callback);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                if (callback != null) {
                    callback.onFailure(getFailedString(e));
                }
            }
        });
    }

    @Override
    protected <T> void postData(final Context context, String url, String body, final RequestCallBack<T> callback) {
        DMLog.i(TAG, "url：" + url);
        PostStringBuilder postStringBuilder = OkHttpUtils.postString().url(url).content(body).mediaType(MediaType.parse("application/json; charset=utf-8"));
        if (!TextUtils.isEmpty(TokenManager.getInstance().getToken(context))) {
            postStringBuilder.addHeader("Authorization", TokenManager.getInstance().getToken(context));
        }
        postStringBuilder.build().execute(new StringCallback() {
            @Override
            public void onBefore(Request request, int id) {
                if (callback != null) {
                    callback.onStart();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                DMOKHttpUtils.this.onJsonResponse(context, response, callback);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                if (callback != null) {
                    callback.onFailure(getFailedString(e));
                }
            }
        });
    }


    @Override
    protected <T> void uploadFileData(final Context context, String url, Map<String, String> params, String name, Map<String, File> files, final RequestCallBack<T> callback) {
        PostFormBuilder postFormBuilder = OkHttpUtils.post().url(url).files(name, files);
        if (!TextUtils.isEmpty(TokenManager.getInstance().getToken(context))) {
            postFormBuilder.addHeader("Authorization", TokenManager.getInstance().getToken(context));
        }
        if (params != null) {
            postFormBuilder.params(params);
        }
        postFormBuilder.build().execute(new StringCallback() {
            @Override
            public void onBefore(Request request, int id) {
                if (callback != null) {
                    callback.onStart();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                DMOKHttpUtils.this.onJsonResponse(context, response, callback);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                if (callback != null) {
                    callback.onFailure(getFailedString(e));
                }
            }


        });
    }


    @Override
    protected <T> void putData(final Context context, String url, HttpParams params, final RequestCallBack<T> callback) {
        OtherRequestBuilder otherRequestBuilder = OkHttpUtils.put().url(url);
        if (!TextUtils.isEmpty(TokenManager.getInstance().getToken(context))) {
            otherRequestBuilder.addHeader("Authorization", TokenManager.getInstance().getToken(context));
        }
        if (params != null) {
            otherRequestBuilder.requestBody(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), params.toString()));
        }
        otherRequestBuilder.build().execute(new StringCallback() {
            @Override
            public void onBefore(Request request, int id) {
                if (callback != null) {
                    callback.onStart();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                DMOKHttpUtils.this.onJsonResponse(context, response, callback);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                if (callback != null) {
                    callback.onFailure(getFailedString(e));
                }
            }
        });
    }


    protected <T> void onJsonResponse(Context context, String response, RequestCallBack<T> callback) {
        try {
            DMLog.i(TAG, response);
            JSONObject json = new JSONObject(response);
            JsonResult jsonResult;
            if (json.has("code")) {
                if (!authorization(context, json.getString("code"), response)) {
                    return;
                }
                if (json.has("description")) {
                    jsonResult = new JsonResult(json.getString("code"), json.getString("description"));
                } else {
                    jsonResult = new JsonResult(json.getString("code"), "");
                }
            } else {
                jsonResult = new JsonResult("000000", "success", json.toString());
            }


            if (json.has("data")) {
                if (json.get("data") == null || StringUtils.isEmptyOrNull(json.get("data").toString())) {
                    DMOKHttpUtils.this.onSuccess(jsonResult, callback);
                } else {
                    if (callback.mType == String.class) {
                        jsonResult.setObject(json.getString("data"));
                        DMOKHttpUtils.this.onSuccess(jsonResult, callback);
                        return;
                    }
                    if (callback.getTokenType() != null) {
                        Object o = mGson.fromJson(json.getString("data"), callback.getTokenType());
                        jsonResult.setObject(o);
                        DMOKHttpUtils.this.onSuccess(jsonResult, callback);
                    } else {
                        /**
                         * 针对"data":[{"backlogCount":"1","brethCount":"1","parkingCount":"1","roadName":"三五路"},{"backlogCount":"1","brethCount":"2","parkingCount":"2","roadName":"洒物路"}]
                         * T 需要采用List<T>
                         */
                        T t = mGson.fromJson(json.getString("data"), callback.mType);
                        jsonResult.setObject(t);
                        DMOKHttpUtils.this.onSuccess(jsonResult, callback);
                    }
                }
            } else {
                DMOKHttpUtils.this.onSuccess(jsonResult, callback);
            }
        } catch (Exception e) {
            e.printStackTrace();
            DMLog.i(TAG, e.getMessage());
            DMOKHttpUtils.this.onFailed("服务器异常，请稍后再试", callback);
        }
//        catch (ClassCastException | JSONException e) {
//            e.printStackTrace();
//            DMOKHttpUtils.this.onFailed("服务器异常，请稍后再试", callback);
//        }

    }

    private void onFailed(String msg, RequestCallBack callback) {
        if (callback != null) {
            callback.onFailure(msg);
        }
    }

    private <T> void onSuccess(JsonResult<T> result, RequestCallBack callback) {
        if (callback != null) {
            callback.onSuccess(result);
        }
    }

    /**
     * 校验权限状态(如token是否失效)
     *
     * @param context
     * @param code
     * @param json
     * @return
     */
    private boolean authorization(Context context, String code, String json) {
        if (context instanceof AuthorizationCheckListener && !StringUtils.isEmptyOrNull(code)) {
            AuthorizationCheckListener authorizationCheckListener = (AuthorizationCheckListener) context;
            List<String> invalidCodes = authorizationCheckListener.getInvalidCodes();
            if (invalidCodes != null && invalidCodes.contains(code)) {
                authorizationCheckListener.doInvalidCodeAction(code, json);
                return false;
            }
        }
        return true;
    }

    private String getFailedString(Exception e) {
        DMLog.i(TAG, e.getMessage());
        if (e instanceof IOException) {
            return "网络异常，请稍后再试";
        } else {
            return "服务器连接异常，请稍后再试";
        }
    }

}
